//
//  HZTabBarController.m
//  HZTC_Stock
//
//  Created by MayerF on 2017/5/24.
//  Copyright © 2017年 MayerF. All rights reserved.
//

#import "HZTabBarController.h"
#import "HZNavViewController.h"
#import "HZMarketViewController.h"
#import "HZNetworkTool.h"

#import "HZApiTool.h"
#import "NSString+NormalTool.h"
//配资
//#import "HZPeiziHomeViewController.h"
//#import "HZPeiziAccoutMoneyVC.h"
//#import "HZPeiziBuySellVC.h"
//#import "HZPeiziCancelOrderVC.h"
//#import "HZPeiziAddMoneyVC.h"
//#import "HZPeiziMyStockVC.h"
//#import "HZPeiziWeiTuoVC.h"
//#import "HZPeiziDealVC.h"
//#import "HZPeiziMoneFlowVC.h"
//#import "HZPeiziMoneyOutVC.h"
//#import "HZPeiziMoreAccountVC.h"


@interface HZTabBarController ()<UITabBarControllerDelegate>
@property (nonatomic, assign)CGFloat fBegainSlidePointX; //开始滑动点X坐标
@end

@implementation HZTabBarController
- (UIView *)pAlphaView
{
    if (!_pAlphaView) {
        _pAlphaView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame))];
        _pAlphaView.backgroundColor = [UIColor blackColor];
        _pAlphaView.alpha = 0.f;
        _pAlphaView.hidden = YES;
    }
    return _pAlphaView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.tabBar.tintColor = kMYHexToRGB(0xf85256, 1);
    self.tabBar.barTintColor = [UIColor whiteColor];
    self.tabBar.translucent = NO;
    self.delegate = self;
    
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
    [SVProgressHUD setMinimumDismissTimeInterval:1.7];
    [SVProgressHUD setFadeInAnimationDuration:0];
    [SVProgressHUD setFadeOutAnimationDuration:0.03];
    [HZNetworkTool shareNetworkTool];
//    BOOL isInstall = [HZUserManager getUserDefaultBoolValueWithkey:kHZInstallAPPFlag];
//    if (!isInstall) {//首次安装/卸载重装
//        [HZUserManager saveUserDefaultBoolValue:YES key:kHZInstallAPPFlag];
//        [HZUserManager deleteKeyChainDataWithKey:kHZUserKeyChainAccount];
//        [HZUserManager deleteKeyChainDataWithKey:kHZUserKeyChainPwd];
//    }
//
//    NSString *account = [HZUserManager getKeyChainDataWithkey:kHZUserKeyChainAccount];
//    NSString *pwd = [HZUserManager getKeyChainDataWithkey:kHZUserKeyChainPwd];
//    if (account && pwd) {
//        NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
//                              @"300001", kAPIFuctionKey,
//                              account, @"mobile",
//                              pwd, @"password",
//                              nil];
//        [self sendAutoLoginWithLoginfo:dict];
//    }
//    ThemeManager.manager.themeType = [HZCommonTool toolThemeType];
    
    
    // 查看是否正常显示app
    [HZUserManager manager].isNormalShow = YES;
    
    if ([HZUserManager manager].isNormalShow) {
        [self p_setControllers];
    }else {
        [self p_setSpecialControllers];
        [self p_setSpecialDefaultState];
    }
    
    [self.view addSubview:self.pAlphaView];
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(alphaViewGesture:)];
    UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(alphaViewGesture:)];
    [_pAlphaView addGestureRecognizer:tapGesture];
    [_pAlphaView addGestureRecognizer:panGesture];
    
    [self checkVersion];
}
//发送自动登录请求
- (void)sendAutoLoginWithLoginfo:(NSDictionary *)loginfo
{
    [HZApiManager apiPostParams:loginfo success:^(id objc) {
        [HZUserManager manager].isLogined = YES;
        [HZUserManager manager].nickName = loginfo[@"mobile"];
        [self p_requestPeizi];
    } failure:^(NSError *error) {
//        [SVProgressHUD showErrorWithStatus:error.domain];
    }];
}
// 请求是否显示配资入口
- (void)p_requestPeizi
{
    [HZApiManager apiPostParams:@{kAPIFuctionKey: @"300034"} success:^(id objc) {
        if ([objc isKindOfClass:[NSArray class]]) {
            NSArray *result = (NSArray *)objc;
            if (result.count > 0) {
                [HZUserManager manager].isVip = YES;
            }
        }
    } failure:^(NSError *error) {
//        [SVProgressHUD showErrorWithStatus:error.domain];
    }];
}
//检测是否有最新版本
- (void)checkVersion
{
    [HZApiTool getNoCacheUrl:@"http://www.zzyqcl.com/version/ios/latest" params:nil success:^(id x) {
        NSDictionary *dict = (NSDictionary *)x;
        NSString *version = dict[@"version"];
        NSString *url = dict[@"url"];
//        NSDictionary *configDict = dict[@"config"];
//        if ([configDict.allKeys containsObject:kAppVersion]) {
//            NSDictionary *dict = configDict[kAppVersion];
//            if ([dict.allKeys containsObject:@"online"]) {
//                BOOL isOnline = [dict[@"online"] boolValue];
//                if (isOnline && ![HZUserManager manager].isNormalShow) {
//                    [HZUserManager manager].isNormalShow = YES;
//                    [HZCommonTool writeShow:isOnline];
//                    [self p_setControllers];
//                }
//            }
//        }
    
        __block BOOL isHaveNewVer = false;
        NSArray *latestVer = [version componentsSeparatedByString:@"."];
        NSArray *localVer = [kAppVersion componentsSeparatedByString:@"."];
        if (latestVer.count == localVer.count) {
            [latestVer enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                NSInteger nLatestVer = [obj integerValue];
                NSInteger nLocalVer = [localVer[idx] integerValue];
                if (nLocalVer < nLatestVer) {
                    isHaveNewVer = YES;
                    *stop = YES;
                }else if (nLocalVer > nLatestVer) {
                    *stop = YES;
                }
            }];
        }
//        NSString *subStr = [version deleteSomeString:@"."];
//        NSString *localStr = [kAppVersion deleteSomeString:@"."];
        if (isHaveNewVer) {
            UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"已有新版本，是否更新？" message:nil preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *actionOk = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
            }];
            UIAlertAction *actionCancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
            [alertVC addAction:actionOk];
            [alertVC addAction:actionCancel];
            [self presentViewController:alertVC animated:YES completion:nil];
        }
    } failure:^(NSError *error) {
        //@"https://itunes.apple.com/cn/app/id1253811173"
    }];
}
#pragma mark -
#pragma mark private
- (void)p_setControllers
{
    NSString *homeUrl = [NSString stringWithFormat:@"https://app.hexinsec.com/client/app/index.html?sessionId=%@#!/adviser", [HZUserManager manager].session];
    NSString *stockUrl = [NSString stringWithFormat:@"https://app.hexinsec.com/client/app/index.html?sessionId=%@#!/golden_share", [HZUserManager manager].session];
    NSString *meUrl = [NSString stringWithFormat:@"https://app.hexinsec.com/client/app/index.html?sessionId=%@#!/my", [HZUserManager manager].session];
    UIViewController *homeVC = [[MYRouter shared] matchController:kRouterLoadWeb params:@{@"url": homeUrl}];
    UIViewController *stockVC = [[MYRouter shared] matchController:kRouterLoadWeb params:@{@"title": @"专家组合",
                                                                                           @"url": stockUrl}];
    UIViewController *changeVC = [[MYRouter shared] matchController:kRouterLoadWeb params:@{@"title": @"机会",
                                                                                            @"url": @"https://app.hexinsec.com/client/app/#!/home"}];
    UIViewController *meVC = [[MYRouter shared] matchController:kRouterLoadWeb params:@{@"title": @"我的",
                                                                                        @"url": meUrl}];
//    UIViewController *meVC = [[MYRouter shared] matchController:kRouterLoadWeb params:@{@"url": @"http://192.168.4.146:3000/service"}];
    UINavigationController *homeNavVC = [[HZNavViewController alloc] initWithRootViewController:homeVC];
//    UINavigationController *marketNavVC = [[HZNavViewController alloc] initWithRootViewController:[HZMarketViewController new]];
    UINavigationController *stockNavVC = [[HZNavViewController alloc] initWithRootViewController:stockVC];
    UINavigationController *changedNavVC = [[HZNavViewController alloc] initWithRootViewController:changeVC];
    UINavigationController *meNavVC = [[HZNavViewController alloc] initWithRootViewController:meVC];
    
    [self setViewControllers:@[homeNavVC, stockNavVC, changedNavVC, meNavVC] animated:YES];
    [self p_setDefaultState];
}
- (void)p_setDefaultState
{
    NSArray *titleArray = [NSArray arrayWithObjects:
                           @"投顾",
                           @"金股",
                           @"自选",
                           @"机会",
                           @"我的", nil];
    NSArray *imageArray = [NSArray arrayWithObjects:
                           @"home",
                           @"stock",
                           @"market",
                           @"change",
                           @"mine", nil];
    NSArray *imageSelArray = [NSArray arrayWithObjects:
                           @"home_sel",
                           @"stock_sel",
                           @"market_sel",
                           @"change_sel",
                           @"mine_sel", nil];
    NSArray *barItemArray = self.tabBar.items;
    for (int i = 0; i < barItemArray.count; i++) {
        UITabBarItem *barItem = barItemArray[i];
        barItem.titlePositionAdjustment = UIOffsetMake(0, -5);
        barItem.imageInsets = UIEdgeInsetsMake(-3, 0, 3, 0);
        NSString *title = titleArray[i];
        UIImage *image = [UIImage imageNamed:imageArray[i]];
        UIImage *imageSel = [UIImage imageNamed:imageSelArray[i]];
        [barItem setTitle:title];
        [barItem setImage:[image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
        [barItem setSelectedImage:[imageSel imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
    }
    [[UITabBarItem appearance] setTitleTextAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:12],
                                                        NSForegroundColorAttributeName: kMYHexToRGB(0x7f8699, 1)
                                                        } forState:UIControlStateNormal];
    [[UITabBarItem appearance] setTitleTextAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:12],
                                                        NSForegroundColorAttributeName: kMYHexToRGB(0xef1d2e, 1)
                                                        } forState:UIControlStateSelected];
}
- (void)p_setSpecialControllers
{
//    UINavigationController *homeNavVC = [[HZNavViewController alloc] initWithRootViewController:[HZHomeViewController new]];
//    UINavigationController *marketNavVC = [[HZNavViewController alloc] initWithRootViewController:[HZMarketViewController new]];
//    //    UINavigationController *sellNavVC = [[HZNavViewController alloc] initWithRootViewController:[HZWebViewController new]];
//    UINavigationController *finishedNavVC = [[HZNavViewController alloc] initWithRootViewController:[HZNoticeViewController new]];
//    UINavigationController *meNavVC = [[HZNavViewController alloc] initWithRootViewController:[HZSettingViewController new]];
//
//    [self setViewControllers:@[homeNavVC, marketNavVC, finishedNavVC, meNavVC] animated:YES];
}
- (void)p_setSpecialDefaultState
{
    NSArray *titleArray = [NSArray arrayWithObjects:
                           @"首页",
                           @"行情",
//                           @"资讯",
                           @"公告",
                           @"设置",
                           nil];
    NSArray *imageArray = [NSArray arrayWithObjects:
                           @"home",
                           @"home_stock",
//                           @"home_info",
                           @"home_notice",
                           @"home_me",
                           nil];
    NSArray *imageSelArray = [NSArray arrayWithObjects:
                              @"home_selected",
                              @"home_stock_sel",
//                           @"home_info_sel",
                              @"home_notice_sel",
                              @"home_me_sel",
                              nil];
    NSArray *barItemArray = self.tabBar.items;
    for (int i = 0; i < barItemArray.count; i++) {
        UITabBarItem *barItem = barItemArray[i];
        NSString *title = titleArray[i];
        UIImage *image = [UIImage imageNamed:imageArray[i]];
        UIImage *imageSel = [UIImage imageNamed:imageSelArray[i]];
        [barItem setTitle:title];
        [barItem setImage:image];
        [barItem setSelectedImage:imageSel];
    }
}

#pragma mark -
#pragma mark action
- (void)alphaViewGesture:(UIGestureRecognizer *)gesture
{
    if ([gesture isKindOfClass:[UITapGestureRecognizer class]]) {
        [[NSNotificationCenter defaultCenter] postNotificationName:kHiddenLeftController object:nil];
    }else if ([gesture isKindOfClass:[UIPanGestureRecognizer class]]) {
        switch (gesture.state) {
            case UIGestureRecognizerStateBegan:
            {
                CGPoint pPoint = [gesture locationInView:_pAlphaView];
                _fBegainSlidePointX = pPoint.x;
            }
                break;
            case UIGestureRecognizerStateChanged:
            {
                CGPoint pPoint = [gesture locationInView:_pAlphaView];
                NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                                      @(_fBegainSlidePointX - pPoint.x), @"distance",
                                      @(UIGestureRecognizerStateChanged), @"state", nil];
                [[NSNotificationCenter defaultCenter] postNotificationName:kGradualHiddenLeftController object:dict];
            }
                break;
            case UIGestureRecognizerStateEnded:
            {
                CGPoint pPoint = [gesture locationInView:_pAlphaView];
                NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                                      @(_fBegainSlidePointX - pPoint.x), @"distance",
                                      @(UIGestureRecognizerStateEnded), @"state", nil];
                [[NSNotificationCenter defaultCenter] postNotificationName:kGradualHiddenLeftController object:dict];
            }
                break;
                
            default:
                break;
        }
    }
}
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
    if (self.selectedIndex == 1 && [HZUserManager manager].isVip && [HZUserManager manager].isNormalShow) {
        [HZUserManager manager].peiziWindow.hidden = NO;
    }else {
        [HZUserManager manager].peiziWindow.hidden = YES;
    }
}

@end
